<!-- 商品上架 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${storehouse}-${zoneItem.name}-${classifyItem.cateName}-商品上架`"
            @back="() => $router.go(-1)"
        >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="商品名称">
                            <a-input v-model="goodsName" allow-clear placeholder="请输入商品名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24" v-if="showClassify">
                        <a-form-item label="商品分类">
                            <a-select v-model="classifyId" placeholder="请选择" allowClear @change="selClassify">
                                <a-select-option v-for="(item) in classifyList" :key="item.id" :value="item.id">{{item.cateName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="商品信息">
                            <a-select v-model="goodsId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in goodsList" :key="i" :value="item.goodsId">{{item.goodsName}}-{{item.colorName}}-{{item.grade}}-{{item.specName}}-{{item.remarks}}-{{item.description}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="颜色">
                            <a-select v-model="colorId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in colorsList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="等级">
                            <a-select v-model="grade" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in gradeList" :key="i" :value="item.name">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="状态">
                            <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="16" :sm="24" v-if="showClassify">
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <a-button icon="plus" @click="add()">新增</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  
        <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" border :scroll="{ x: 1800, }">
            <div slot="imageUrl" slot-scope="imageUrl">
                <img v-if="imageUrl && imageUrl != ''" style="width: 100px;height: 50px" :src="imageUrl" alt="">
                <div v-else>-</div>
            </div>
            <div slot="grade" slot-scope="grade" > 
                <div v-for="(item,i) in gradeList" :key="i">
                    <a-tag v-if="item.name == grade" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="specId" slot-scope="specId">
                <div v-for="(item,i) in specList" :key="i">
                    <a-tag v-if="item.id == specId" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="colorId" slot-scope="colorId">
                <div v-for="(item,i) in colorsList" :key="i">
                    <a-tag v-if="item.id == colorId" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="lastTime" slot-scope="lastTime">   
                <div>{{lastTime ? lastTime : '-'}}</div>
            </div>
            <div slot="latestTime" slot-scope="latestTime">   
                <div>{{latestTime ? latestTime : '-'}}</div>
            </div>
            <div slot="limitPurchaseQuantity" slot-scope="limitPurchaseQuantity">   
                <div v-if="zoneItem.id == '0'">{{limitPurchaseQuantity}}</div>
                <div v-else>-</div>
            </div>
            <div slot="discountStatus" slot-scope="discountStatus,record">   
                <div v-if="zoneItem.id == '0'">
                    <a-button v-if="discountStatus == '1'" type="link" class="errorColor" @click="closeDis(record)">关闭</a-button>
                    <a-button v-else type="link" @click="openDis(record)">开启</a-button>
                </div>
                <div v-else-if="record.areaId == disZoneId">
                    <div>
                        <div>开始时间：{{record.discountStartTime}}</div>
                        <div>循环天数：{{record.cycleDays}}天</div>
                        <div>折扣比例：{{record.discountRatio * 100}}%</div>
                    </div>
                </div>
                <div v-else>-</div>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="上架" un-checked-children="下架" disabled :checked="status == 1 ? true : false" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button class="errorColor" type="link">删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>
        </a-page-header>

        <!-- 增删改商品设置 -->
        <a-modal
            title="添加、修改上架商品信息"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            width="50%"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item :colon="false">
                        <div class="flex alignCenter">
                            <a-select show-search  v-model="item.goodsId" placeholder="请选择" @search="handleSearch" @change="selGoods">
                                <a-select-option v-for="(itm) in goodsList" :value="itm.goodsId+','+itm.id+','+itm.goodsName+','+itm.colorName+','+itm.grade+','+itm.specName+','+itm.remarks+','+itm.colorId+','+itm.specId" :key="itm.id"><span v-if="itm.isListed == '1'" style="color: red">(已上架)</span>{{itm.goodsName}}-{{itm.colorName}}-{{itm.grade}}-{{itm.specName}}-{{itm.remarks}}-{{itm.description}}</a-select-option>
                            </a-select> 
                            <a-button type="link" @click="updateGoods">修改</a-button>
                        </div>
                        <template slot="label">
                            <!-- <span v-if="hasGoods">商品信息<span style="color: red">（已上架）</span>:</span>
                            <span v-else>商品信息:</span> -->
                            <span>商品信息：</span>
                        </template>
                    </a-form-item>
                    <a-form-item label="建议售价" >
                        <!-- <a-input v-model="suggestSP" readonly :placeholder="`请输入建议售价`" suffix="元" allow-clear ></a-input> -->
                        <div>{{suggestSP}}元</div>
                    </a-form-item>
                    <a-form-item label="建议原价" >
                        <!-- <a-input v-model="suggestOP" readonly :placeholder="`请输入建议原价`" suffix="元" allow-clear ></a-input> -->
                        <div>{{suggestOP}}元</div>
                    </a-form-item>
                    <a-form-item label="商品售价" >
                        <a-input v-model="item.sellingPrice" :placeholder="`请输入商品售价`" suffix="元" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="商品原价" >
                        <a-input v-model="item.originalPrice" :placeholder="`请输入商品原价`" suffix="元" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="商品销量" >
                        <a-input v-model="item.salesVolume" :placeholder="`请输入商品销量`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="库存" v-if="roleLength >= 218 || zoneItem.id != '0'">
                        <a-input v-model="item.stock" :placeholder="`请输入商品库存`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="每日限购" v-if="zoneItem.id != '0'">
                        <a-input v-model="item.limitPurchaseQuantity" :placeholder="`请输入每人每日限购数量`" allow-clear ></a-input>
                    </a-form-item>
                    <!-- <a-form-item label="商品销量" >
                        <a-input v-model="item.updateSalesVolume" :placeholder="`请输入商品销量`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="库存" v-if="roleLength >= 218 || zoneItem.id != '0'">
                        <a-input v-model="item.updateStock" :placeholder="`请输入商品库存`" allow-clear ></a-input>
                    </a-form-item> -->
                    <a-form-item label="秒杀时间" v-if="item.isFlashSale == '1'">
                        <a-range-picker :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss" v-model="rangePicker" :placeholder="['开始时间', '结束时间']" @change="seckillTimeChange" @ok="seckillTimeOk"/>
                    </a-form-item>
                    <a-form-item label="打折开始时间" v-if="zoneItem.id == disZoneId">
                        <a-date-picker show-time :disabled-date="disabledDate" format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" v-model="item.discountStartTime" :placeholder="'打折开始时间'"/>
                    </a-form-item>
                    <a-form-item label="循环天数" v-if="zoneItem.id == disZoneId">
                        <a-input v-model="item.cycleDays" :placeholder="`请输入打折循环天数`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="折扣比例" v-if="zoneItem.id == disZoneId">
                        <a-input v-model="item.discountRatio" :placeholder="`请输入商品折扣比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 修改商品详情信息 -->
        <a-modal
            title="添加、修改商品详情信息"
            :visible="goodsDetailVisible"
            :confirm-loading="goodsDetailConfirmLoading"
            @ok="goodsDetailHandleOk"
            @cancel="goodsDetailVisible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="商品等级" >
                        <div style="display: flex">
                            <a-select show-search v-model="goods.grade" placeholder="请选择" v-if="gradeSel">
                                <a-select-option v-for="(itm) in gradeList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>   
                            <a-input v-else v-model="goods.grade" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="gradeSel = !gradeSel" :type="gradeSel ? 'primary' : 'danger'">{{gradeSel ? '默认' : '恢复'}}</a-button>
                        </div>
                    </a-form-item>
                    <a-form-item label="商品颜色">
                        <a-select show-search  v-model="goods.colorId" placeholder="请选择">
                            <a-select-option v-for="(itm) in colorsList" :value="itm.name +',' +itm.id" :key="itm.id">{{itm.name}}</a-select-option>
                        </a-select>       
                    </a-form-item>
                    <a-form-item label="周期" >
                        <a-select show-search  v-model="goods.specId" placeholder="请选择">
                            <a-select-option v-for="(itm) in specList" :value="itm.name +',' +itm.id" :key="itm.id">{{itm.name}}</a-select-option>
                        </a-select>   
                    </a-form-item>
                    <a-form-item label="销售价上浮" >
                        <a-input v-model="goods.spFloatRatio" :placeholder="`请输入销售价上浮比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="原价上浮" >
                        <a-input v-model="goods.opFloatRatio" :placeholder="`请输入原价上浮比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="商品花型">   
                        <div style="display: flex">
                            <a-select show-search v-model="goods.flowerPattern" placeholder="请选择" v-if="flowerSel">
                                <a-select-option v-for="(itm) in flowerPatternList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>  
                            <a-input v-else v-model="goods.flowerPattern" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="flowerSel = !flowerSel" :type="flowerSel ? 'primary' : 'danger'">{{flowerSel ? '默认' : '恢复'}}</a-button>
                        </div>  
                    </a-form-item>
                    <a-form-item label="枝干">
                        <div style="display: flex">
                            <a-select show-search v-model="goods.description" placeholder="请选择" v-if="descSel">
                                <a-select-option v-for="(itm) in descriptionList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>   
                            <a-input v-else v-model="goods.description" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="descSel = !descSel" :type="descSel ? 'primary' : 'danger'">{{descSel ? '默认' : '恢复'}}</a-button>
                        </div>     
                    </a-form-item>
                    <a-form-item label="单位">
                        <div style="display: flex">
                            <a-select show-search v-model="goods.remarks" placeholder="请选择" v-if="remarkSel">
                                <a-select-option v-for="(itm) in remarkList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>  
                            <a-input v-else v-model="goods.remarks" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="remarkSel = !remarkSel" :type="remarkSel ? 'primary' : 'danger'">{{remarkSel ? '默认' : '恢复'}}</a-button>
                        </div>     
                    </a-form-item>
                    <a-form-item label="商品备注" >
                        <a-input v-model="goods.notes" :placeholder="`请输入商品备注信息`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="图片">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="goods.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 修改折扣配置信息 -->
        <a-modal
            title="添加、修改折扣配置信息"
            :visible="goodsDisVisible"
            :confirm-loading="goodsDisConfirmLoading"
            @ok="goodsDisHandleOk"
            @cancel="goodsDisVisible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item :colon="false">
                        <div class="flex alignCenter">
                            <a-select show-search disabled v-model="item.goodsId" placeholder="请选择" @search="handleSearch" @change="selGoods">
                                <a-select-option v-for="(itm) in goodsList" :value="itm.goodsId+','+itm.id+','+itm.goodsName+','+itm.colorName+','+itm.grade+','+itm.specName+','+itm.remarks+','+itm.colorId+','+itm.specId" :key="itm.id"><span v-if="itm.isListed == '1'" style="color: red">(已上架)</span>{{itm.goodsName}}-{{itm.colorName}}-{{itm.grade}}-{{itm.specName}}-{{itm.remarks}}-{{itm.description}}</a-select-option>
                            </a-select> 
                            <a-button type="link" @click="updateGoods">修改</a-button>
                        </div>
                        <template slot="label">
                            <span>商品信息：</span>
                        </template>
                    </a-form-item>
                    <a-form-item label="打折开始时间">
                        <a-date-picker show-time :disabled-date="disabledDate" format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" v-model="item.discountStartTime" :placeholder="'打折开始时间'"/>
                    </a-form-item>
                    <a-form-item label="循环天数" >
                        <a-input v-model="item.cycleDays" :placeholder="`请输入打折循环天数`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="折扣比例" >
                        <a-input v-model="item.discountRatio" :placeholder="`请输入商品折扣比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="库存">
                        <a-input v-model="item.stock" :placeholder="`请输入商品库存`" allow-clear ></a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryClassify } from '@/api/mall/classify';
import { queryGoodsGeneral , queryGoodsCommonConfig , queryGoodsLists , upadteGoodsLists , queryGoodsDetail , queryGoodsSuggestPrice , updateGoodsDetail } from '@/api/newMall';
import moment from 'moment';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            storehouseId: JSON.parse(localStorage.getItem('storehouseId')),
            zoneItem: JSON.parse(localStorage.getItem('zoneItem')),
            classifyItem: JSON.parse(localStorage.getItem('classifyItem')),
            goodsName: this.$route.query.goodsName ?? '', // 商品名称
            showClassify: this.$route.query.goodsName !== null && this.$route.query.goodsName !== undefined ? true : false,
            goodsList: [],
            classifyList: [],
            goodsId: undefined,
            colorId: undefined,
            colorsList: [],
            grade: undefined,
            gradeList: [],
            status: undefined,
            selGoodsName: '',
            statusList: [
                { id: '1', name: '上架'},
                { id: '0', name: '下架'},
            ],
            isSeckillList: [
                { id: '0', name: '否'},
                { id: '1', name: '是'},
            ],
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            confirmLoading: false,
            visible: false,
            columns,
            item: {
                id: '',
                goodsId: undefined, // 商品设置信息
                goodsDetailsId: undefined, // 商品详情ID
                originalPrice: '', // 原价
                sellingPrice: '', // 售价
                updateStock: '', // 库存
                description: undefined, // 描述
                updateSalesVolume: '', // 销量
                isFlashSale: '0', // 是否限时抢购
                flashSaleStartTime: '',
                flashSaleEndTime: '',
                status: '1', // 状态，1：上架，0：下架
                stock: '',
                salesVolume: '',
                limitPurchaseQuantity: '', // 每人每日限购数量
                relationId: undefined, // 折扣商品关联ID
                discountStartTime: undefined, // 折扣开始时间
                cycleDays: '', // 打折循环天数
                discountRatio: '', // 打折折扣比例
                discountStatus: '0', // 折扣状态，1：开启，0：关闭

            },
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            roleLength: this.$store.getters.roles.length,
            suggestOP: 0, // 建议原价
            suggestSP: 0, // 建议售价
            rangePicker: [],
            hasGoods: false,
            classifyId: undefined,
            areaList: [],
            goods: {
                id: '',
                goodsId: undefined, // 商品设置信息
                colorId: undefined, // 颜色ID
                grade: undefined, // 商品等级
                specId: undefined, // 商品规格
                opFloatRatio: '', // 原价浮动比例
                spFloatRatio: '', // 售价上浮比例
                notes: '', // 商品备注信息
                description: undefined, // 描述
                remarks: undefined, // 备注
                flowerPattern: undefined, // 花型
                status: '1', // 状态，1：上架，0：下架
            },
            goodsDetailVisible: false,
            goodsDetailConfirmLoading: false,
            fileList: [],
            gradeSel: true,
            flowerSel: true,
            descSel: true,
            remarkSel: true,
            flowerPatternList: [],
            specList: [],
            remarkList: [],
            descriptionList: [],
            disZoneId: 201, // 折扣区分区ID
            disStartTime: '', // 折扣开始时间，用于区分是否修改了打折开始时间
            goodsDisVisible: false,
            goodsDisConfirmLoading: false,
            merchantId: '0',
        };
    },
    async created(){
        try {
            if(this.showClassify){
                await this.getClassify();
            }
            await this.getColors();
            // await this.getArea();
            // await this.getStoreHouse();
            this.getGoods();
            await this.getDescription('3');
            await this.getDescription('4');
            await this.getDescription('5');
            await this.getDescription('6');
            await this.getDescription('1');
            await this.getDescription('7');
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        moment,
        async handleSearch(goodsName){
            console.log(goodsName,'name')
            await this.getGoods(goodsName);
        },
        // 获取商品选择列表
        getGoods(selGoodsName,goodsDetailId){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId': _this.brandId,
                    'id': goodsDetailId,
                    'cateId': _this.classifyItem.id,
                    'storehouseId': _this.storehouseId,
                    'areaId': _this.zoneItem.id,
                    'goodsName': selGoodsName,
                    'status': '1',
                    'page': 0,
                    'size': 99,
                }
                queryGoodsDetail(params)
                .then(res => {
                    if(res.success){
                        if(!goodsDetailId){
                            _this.goodsList = res.data.content;
                        }
                        resolve(res.data.content);
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取商品设置
        async getData(){
            let _this = this;
            console.log(_this.page,'page')
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.zoneItem.id,
                'cateId': _this.classifyItem.id,
                'goodsName': _this.goodsName,
                'goodsId': _this.goodsId,
                'colorId': _this.colorId,
                'grade': _this.grade,
                'specId': _this.spec,
                'status': _this.status,
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            try {
                var data = await _this._searchGoods(params);
                _this.isload = false;
                _this.dataList = data.content;
                _this.total = data.totalElements;
            } catch (error) {
                _this.isload = false;
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _searchGoods(params){
            return new Promise((resolve,reject) => {
                queryGoodsLists(params)
                .then(res => {
                    if(res.success){
                        resolve(res.data);
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取分类信息
        async getClassify(){
            let _this = this;
            try {
                const params = {
                    'brandId':_this.brandId,
                    // 'parentId':'0',
                    'level': '2',
                    'size': 99,
                    'page': 0,
                }
                _this.classifyList = await _this._queryClassify(params);
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _queryClassify(params,type){
            var _this=this
            return new Promise((resolve,reject) => {
                queryClassify(params)
                .then(res=>{
                    if(res.success){
                        resolve(res.data.content)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取颜色信息
        getColors(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'page': 0,
                    'size': 99,
                    'type': '2',
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        _this.colorsList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取商品说明和备注和分区信息
        getDescription(type){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'type': type,
                    'page': 0,
                    'size': 99,
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        if(type == '3'){
                            _this.gradeList = res.data.content;
                        }else if(type == '4'){
                            _this.specList = res.data.content;
                        }else if(type == '5'){
                            _this.descriptionList = res.data.content;
                        }else if(type == '1'){
                            _this.areaList = res.data.content;
                        }else if(type == '7'){
                            _this.flowerPatternList = res.data.content;
                        }else{
                            _this.remarkList = res.data.content;
                        }
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.item.id = ''
            // this.item.goodsId = undefined
            this.item.originalPrice = '';
            this.item.sellingPrice = '';
            this.item.updateStock = '';
            this.item.updateSalesVolume = '';
            this.item.stock = '';
            this.item.salesVolume = '';
            this.item.sellingPrice = '';
            this.item.sellingPrice = '';
            this.item.isFlashSale = '0';
            this.suggestOP = '';
            this.suggestSP = '';
            if(this.zoneItem.name == '秒杀区'){
                this.item.isFlashSale = '1';
            }else{
                this.item.isFlashSale = '0';
            }
            this.item.merchantId = '0';
            this.item.limitPurchaseQuantity = 999999
            this.item.status = '1';
            this.item.relationId = undefined;
            this.hasGoods = false;
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item))
            if(item.flashSaleStartTime != '' && item.flashSaleStartTime && item.flashSaleStartTime != 'null'){
                this.rangePicker = [moment(item.flashSaleStartTime),moment(item.flashSaleEndTime)]
            }
            this.item.goodsId = item.goodsId + ',' + item.goodsDetailsId + ',' + item.goodsName + ',' + item.colorName + ',' + item.grade + ',' + item.specName + ',' + item.remarks
            this.item.discountRatio = this.item.discountRatio ? this.item.discountRatio * 100 : this.item.discountRatio;
            this.item.discountStartTime = undefined;
            this.fileList = [];
            this.visible = true;
        },
        // 选择图片
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        // 确定添加、修改
        async handleOk(){
            let _this = this
            if(_this.item.goodsId === undefined){
                _this.$message.warning('请选择商品');
                return
            }
            if(_this.item.originalPrice === ''){
                _this.$message.warning('请输入商品原价');
                return
            }
            if(_this.item.sellingPrice === ''){
                _this.$message.warning('请输入商品售价');
                return
            }
            if(_this.item.areaId == _this.disZoneId && _this.item.id != '' && _this.item.discountStartTime != undefined){
                _this.$confirm({
                    title: '温馨提示',
                    content: '修改打折开始时间会初始化打折轮数，是否确认修改？',
                    onOk() {
                        _this._updateGoods();
                    },
                    onCancel() {},
                });
                return;
            }else{
                _this._updateGoods();
            }
            
            // if(_this.item.id == ''){
            //     // 添加的时候，分别在活动区添加商品
            //     for (let index = 0; index < _this.areaList.length; index++) {
            //         const element = _this.areaList[index];
            //         params.areaId = element.id;
            //         await _this._saveGoods(params);
            //     }
            // }
            // upadteGoodsLists(params)
            // .then(res=>{
            //     _this.confirmLoading = false
            //     if(res.success){
            //         _this.$notification['success']({
            //             message: '提示',
            //             description: _this.item.id == '' ? '添加成功' : '修改成功',
            //             duration: 8,
            //         })
            //         _this.visible = false
            //         _this.getData()
            //     }else{
            //         _this.$notification['error']({
            //             message: '提示',
            //             description: res.errMessage,
            //             duration: 8,
            //         })
            //     }
            // })
        },
        async _updateGoods(){
            let _this = this;
            _this.confirmLoading = true;
            var params = {
                'id': _this.item.id,
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.zoneItem.id,
                'goodsId': _this.item.goodsId.split(',')[0],
                'goodsDetailsId': _this.item.goodsId.split(',')[1],
                'originalPrice': _this.item.originalPrice,
                'sellingPrice': _this.item.sellingPrice,
                'updateStock': _this.item.stock,
                'updateSalesVolume': _this.item.salesVolume,
                'isFlashSale': _this.item.isFlashSale,
                'flashSaleStartTime': _this.item.flashSaleStartTime,
                'flashSaleEndTime': _this.item.flashSaleEndTime,
                'limitPurchaseQuantity': _this.item.limitPurchaseQuantity,
                'status': _this.item.status,
                'merchantId': _this.item.merchantId,
                'discountStartTime': _this.item.discountStartTime,
                'cycleDays': _this.item.cycleDays,
                'discountRatio': _this.item.discountRatio ? _this.item.discountRatio / 100 : '',
            }
            try {
                await _this._saveGoods(params);
                _this.$notification['success']({
                    message: '提示',
                    description: _this.item.id == '' ? '添加成功' : '修改成功',
                    duration: 8,
                })
                _this.visible = false
                _this.getData()
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _saveGoods(params){
            let _this = this
            return new Promise((resolve,reject) => {
                upadteGoodsLists(params)
                .then(res=>{
                    _this.confirmLoading = false
                    if(res.success){
                        resolve();
                        // _this.$notification['success']({
                        //     message: '提示',
                        //     description: _this.item.id == '' ? '添加成功' : '修改成功',
                        //     duration: 8,
                        // })
                        // _this.visible = false
                        // _this.getData()
                    }else{
                        reject(res.errMessage);
                        // _this.$notification['error']({
                        //     message: '提示',
                        //     description: res.errMessage,
                        //     duration: 8,
                        // })
                    }
                })
            })
        },
        // 删除
        del(item){
            let _this = this;
            const params = {
                'id': item.id,
                'name': item.name,
                'cateId': item.cateId,
                'isDelete': '1'
            }
            upadteGoodsLists(params)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        iptdbclick(item,type){
            console.log('触发双击',type)
            this.updateId = item.id;
            this.upValue = item[type];
            this.upType = type;
            this.item = item;
            console.log(this.upValue,'upvalue')
        },
        iptUpdate(type){
            console.log(this.dataList,'datalist')
            console.log(this.upValue,'upValue')
            this.updateId = ''
            this.iptUpdateEvent(this.item)
        },
        // 修改数据
        iptUpdateEvent(item){
            let _this = this;
            const formData = new FormData();
            if(this.upValue === '' || this.upValue === undefined){
                return;
            }
            formData.append('id', item.id);
            formData.append(this.upType,this.upValue)
            updateGoodsDetail(formData)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        seckillTimeChange(value, dateString) {
            if(dateString[0]){
                this.item.seckillStartTime = dateString[0];
                this.item.seckillEndTime = dateString[1];
            }else{
                this.item.seckillStartTime = '';
                this.item.seckillEndTime = '';
            }
        },
        seckillTimeOk(value) {
            console.log(this.rangePicker,'datestring')
            if(this.rangePicker[0]){
                this.item.seckillStartTime = moment(value[0]).format('YYYY-MM-DD hh:mm:ss');
                this.item.seckillEndTime = moment(value[1]).format('YYYY-MM-DD hh:mm:ss');
            }else{
                this.item.seckillStartTime = '';
                this.item.seckillEndTime = '';
            }
        },
        selGoods(item){
            console.log(item,'item')
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.zoneItem.id,
                'goodsId': item.split(',')[0],
                'goodsDetailsId': item.split(',')[1],
            }
            queryGoodsSuggestPrice(params)
            .then(res => {
                if(res.success){
                    _this.suggestOP = res.data.suggestOP;
                    _this.suggestSP = res.data.suggestSP;
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            });
            const param = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.zoneItem.id,
                'cateId': _this.classifyItem.id,
                'goodsId': item.split(',')[0],
                'goodsName': item.split(',')[2],
                'colorId': item.split(',')[7],
                'grade': item.split(',')[4],
                'specId': item.split(',')[8],
                'page': 0,
            }
            queryGoodsLists(param)
            .then(res => {
                if(res.success){
                    if(res.data.content.length > 0){
                        _this.hasGoods = true;
                    }else{
                        _this.hasGoods = false;
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        seckillTimeChange(value, dateString) {
            if(dateString[0]){
                this.item.flashSaleStartTime = dateString[0];
                this.item.flashSaleEndTime = dateString[1];
            }else{
                this.item.flashSaleStartTime = '';
                this.item.flashSaleEndTime = '';
            }
        },
        seckillTimeOk(value) {
            console.log(this.rangePicker,'datestring')
            if(this.rangePicker[0]){
                this.item.flashSaleStartTime = moment(value[0]).format('YYYY-MM-DD hh:mm:ss');
                this.item.flashSaleEndTime = moment(value[1]).format('YYYY-MM-DD hh:mm:ss');
            }else{
                this.item.flashSaleStartTime = '';
                this.item.flashSaleEndTime = '';
            }
        },
        // 切换分类
        selClassify(id){
            let _this = this;
            if(id){
                for (let index = 0; index < _this.classifyList.length; index++) {
                    const item = _this.classifyList[index];
                    if(item.id == id){
                        _this.classifyItem = JSON.parse(JSON.stringify(item))
                    }
                }
            }else{
                _this.classifyItem = JSON.parse(JSON.stringify({'id': '','cateName': ''}))
            }
            
            _this.getData();
        },
        // 修改商品信息
        async updateGoods(){
            let _this = this;
            if(_this.item.goodsId == undefined){
                _this.$message.warning('请选择需要修改的商品信息');
                return
            }
            console.log(_this.item.goodsId,'goodsId')
            let goodsDetailId = _this.item.goodsId.split(',')[1];
            var updateGoodsList = await _this.getGoods('',goodsDetailId);
            if(updateGoodsList.length > 0){
                _this.goods = JSON.parse(JSON.stringify(updateGoodsList[0]))
            }else{
                _this.$message.warning('暂未获取到相关商品信息');
                return
            }
            this.goods.specId = _this.goods.specName + ',' + _this.goods.specId
            this.goods.colorId = _this.goods.colorName + ',' + _this.goods.colorId
            this.goods.opFloatRatio = _this.goods.opFloatRatio * 100;
            this.goods.spFloatRatio = _this.goods.spFloatRatio * 100;
            this.fileList = [];
            console.log(_this.goods,'goods')
            _this.goodsDetailVisible = true;
        },
        // 确认修改商品详情信息
        goodsDetailHandleOk(){
            let _this = this;
            if(_this.goods.colorId === undefined){
                _this.$message.warning('请选择商品颜色');
                return
            }
            if(_this.goods.grade === undefined){
                _this.$message.warning('请选择商品等级信息');
                return
            }
            if(_this.goods.specId === undefined){
                _this.$message.warning('请选择商品规格信息');
                return
            }
            if(_this.goods.description === undefined){
                _this.$message.warning('请选择商品描述信息');
                return
            }
            if(_this.goods.remarks === undefined){
                _this.$message.warning('请选择商品备注信息');
                return
            }
            if(_this.goods.flowerPattern === undefined){
                _this.$message.warning('请选择商品花型信息');
                return
            }
            _this.goodsDetailConfirmLoading = true;
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', _this.goods.id);
            formData.append('goodsId', _this.goods.goodsId);
            formData.append('colorId', _this.goods.colorId.split(',')[1]);
            formData.append('specId', _this.goods.specId.split(',')[1]);
            formData.append('grade', _this.goods.grade);
            formData.append('opFloatRatio', _this.goods.opFloatRatio / 100);
            formData.append('spFloatRatio', _this.goods.spFloatRatio / 100);
            formData.append('description', _this.goods.description);
            formData.append('remarks', _this.goods.remarks);
            formData.append('notes', _this.goods.notes);
            formData.append('flowerPattern', _this.goods.flowerPattern);
            formData.append('status', _this.goods.status);
            if(_this.fileList.length > 0){
                formData.append('file',_this.fileList[0].originFileObj)
            }
            updateGoodsDetail(formData)
            .then(res=>{
                _this.goodsDetailConfirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.goodsDetailVisible = false
                    _this.getGoods();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        disabledDate(current) {
            // Can not select days before today and today
            return current < moment().startOf('day');
        },
        // 开启折扣管理配置
        openDis(item){
            this.item = JSON.parse(JSON.stringify(item));
            this.item.discountStatus = '1';
            // this.item.relationId = item.id;
            // this.item.id = '';
            this.item.discountStartTime = undefined;
            this.item.cycleDays = '';
            this.item.discountRatio = '';
            this.item.goodsId = item.goodsId + ',' + item.goodsDetailsId + ',' + item.goodsName + ',' + item.colorName + ',' + item.grade + ',' + item.specName + ',' + item.remarks
            this.goodsDisVisible = true;
        },
        async goodsDisHandleOk(){
            let _this = this;
            if(!_this.item.discountStartTime){
                _this.$message.warning('请选择打折开始时间');
                return
            }
            if(_this.item.cycleDays == ''){
                _this.$message.warning('请输入打折循环天数');
                return
            }
            if(_this.item.discountRatio == ''){
                _this.$message.warning('请输入打折比例');
                return
            }
            _this.goodsDisConfirmLoading = true;
            // 再在折扣区添加商品
            var params = {
                'id': _this.item.id,
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.item.areaId,
                'goodsId': _this.item.goodsId.split(',')[0],
                'goodsDetailsId': _this.item.goodsId.split(',')[1],
                'originalPrice': _this.item.originalPrice,
                'sellingPrice': _this.item.sellingPrice,
                'updateStock': '',
                'updateSalesVolume': _this.item.salesVolume,
                'isFlashSale': _this.item.isFlashSale,
                'flashSaleStartTime': _this.item.flashSaleStartTime,
                'flashSaleEndTime': _this.item.flashSaleEndTime,
                'limitPurchaseQuantity': _this.item.limitPurchaseQuantity,
                'discountStatus': _this.item.discountStatus,
                // 'relationId': _this.item.id,
                // 'discountStartTime': _this.item.discountStartTime,
                // 'cycleDays': _this.item.cycleDays,
                // 'discountRatio': _this.item.discountRatio / 100,
                'status': _this.item.status,
                'merchantId': _this.item.merchantId,
            }
            // 先修改商品区商品折扣状态开关为打开状态
            try {
                await _this._saveGoods(params);
                params['id'] = '';
                params['relationId'] = _this.item.id;
                params['discountStartTime'] = _this.item.discountStartTime;
                params['cycleDays'] = _this.item.cycleDays;
                params['updateStock'] = _this.item.stock;
                params['discountRatio'] = _this.item.discountRatio / 100;
                params['status'] = '1';
                params['areaId'] = _this.disZoneId;
                await _this._saveGoods(params);
                _this.$notification['success']({
                    message: '提示',
                    description: '保存成功',
                    duration: 8,
                })
                _this.getData();
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
            _this.goodsDisConfirmLoading = false;
            _this.goodsDisVisible = false
            _this.getData()
        },
        // 关闭折扣商品状态
        async closeDis(item){
            let _this = this;
            _this.$confirm({
                title: '温馨提示',
                content: '是否关闭当前折扣配置？',
                async onOk(){
                    const params = {
                        'relationId': item.id,
                        'brandId': _this.brandId,
                        'areaId': _this.disZoneId,
                    }
                    try {
                        var data = await _this._searchGoods(params);
                        if(data.content.length > 0){
                            const paramsDel = {
                                'id': data.content[0].id,
                                'isDelete': '1'
                            }
                            try {
                                await _this._saveGoods(paramsDel);
                            } catch (error) {
                                _this.$notification['error']({
                                    message: '提示',
                                    description: error,
                                    duration: 8,
                                })
                            }
                        }
                        const paramsClose = {
                            'id': item.id,
                            'brandId': _this.brandId,
                            'discountStatus': '0',
                        }
                        await _this._saveGoods(paramsClose);
                        _this.$notification['success']({
                            message: '提示',
                            description: '操作成功',
                            duration: 8,
                        })
                        _this.getData();
                    } catch (error) {
                        _this.isload = false;
                        _this.$notification['error']({
                            message: '提示',
                            description: error,
                            duration: 8,
                        })
                    }
                },
            })
        },
    }
}

</script>
<style scoped>

</style>